package com.longxi.tianjintianbao.exception;

import android.util.Log;

import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.LazyFragment;
import com.longxi.tianjintianbao.utils.LogUtils;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.longxi.tianjintianbao.utils.NetworkUtils;

import rx.Subscriber;

/**
 * Created by cxw on 2018/3/23.
 */

public abstract class MySubscriber<T> extends Subscriber<T> {

    private BaseActivity mContext;
    private LazyFragment mFragment;

    public MySubscriber(BaseActivity context) {
        LogUtils.i("MySubscriber_saveSubscription",context.getLocalClassName());
        MyApplication.saveSubscriber(context.getLocalClassName(), this);
    }

    @Override
    public void onStart() {
        super.onStart();
        LogUtils.i("tag","MySubscriber.onStart()");
        //接下来可以检查网络连接等操作
        if (!NetworkUtils.isAvailable(MyApplication.getInstance())) {

            MyUtils.showToast("当前网络不可用，请检查网络情况");
            // 一定好主动调用下面这一句,取消本次Subscriber订阅
            if (!isUnsubscribed()) {
                unsubscribe();
            }

            return;
        }
    }

    @Override
    public void onError(Throwable e) {
        LogUtils.e("tag","MySubscriber.throwable ="+e.toString());
        LogUtils.e("tag","MySubscriber.throwable ="+e.getMessage());

        if(e instanceof Exception){
            //访问获得对应的Exception
            onError(ExceptionHandle.handleException(e));
        }else {
            //将Throwable 和 未知错误的status code返回
            onError(new ExceptionHandle.ResponeThrowable(e,ExceptionHandle.ERROR.UNKNOWN));
        }
    }

    public abstract void onError(ExceptionHandle.ResponeThrowable responeThrowable);

    @Override
    public void onCompleted() {
        LogUtils.i("tag","MySubscriber.onComplete()");
    }
}
